package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


/*
* 分类管理
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    CategoryService categoryService;

    /*
    * 新增
    * */
    @PostMapping
    public R<String> add(@RequestBody Category category){
        boolean save = categoryService.save(category);
        return save?R.success("新增成功"):R.error("新增失败");
    }

    /*
    *   分类分页查询
    * */
    @GetMapping("/page")
    public R<Page> page(int page ,int pageSize){
        Page<Category> categoryPage = new Page<>(page,pageSize);
        //按照排序分页查询
        LambdaQueryWrapper<Category> categoryLqw = new LambdaQueryWrapper<>();
        categoryLqw.orderByAsc(Category::getSort);
        categoryService.page(categoryPage,categoryLqw);
        /*HashMap hashMap = new HashMap();
        List<Category> records = categoryPage.getRecords();
        long total = categoryPage.getTotal();*/
        return R.success(categoryPage);
    }

    /*
    *    删除分类
    * */
    @DeleteMapping
    public R<String> delete(Long id){
        //判断是否关联菜品或套餐
        return categoryService.deleteById(id);
    }

    /*
    *   修改分类
    * */

    @PutMapping
    public R<String> update(@RequestBody Category category){
        LambdaQueryWrapper<Category> lwq = new LambdaQueryWrapper<>();
        lwq.eq(Category::getId,category.getId());
        categoryService.update(category,lwq);
        return R.success("修改成功");
    }

    /*
     *   查询菜品分类列表数据
     * */
    @GetMapping("/list")
    public R<List> selectCategory(Integer type){  //对象不为null
        LambdaQueryWrapper<Category> categoryLqw = new LambdaQueryWrapper<>();
        categoryLqw.orderByDesc(true,Category::getSort);
        List<Category> list = categoryService.list(categoryLqw);
        return R.success(list);
    }
}